<?php

// Created by Khanh Nam
class InvoicesController extends Controller {
    public $layout='//layouts/sp';
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'application.filters.RequireLoginFilter',
            ),
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions

                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'invoice-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionIndex($id=NULL, $type=NULL, $custno=NULL, $locno=NULL) {
        SalesPortalLoginCheckerUtil::canUserAccessCustomer($custno);
        switch ($type) {
            case Invoice::TYPE_QUOTE:
                
                $location = Locations::model()->find('custno=:custno AND locno=:locno', array(
                    'custno' => $custno,
                    'locno' => $locno)
                );
                if ($location == NULL) {
                    throw new CHttpException(404, 'The requested page does not exist.');
                }
                $this->render('index', array(
                    'location' => $location,
                    'type' => $type
                ));
                break;
            case Invoice::TYPE_SALES_ORDERS:

                $quote = $this->loadModel($id);
                $this->render('index', array(
                    'model' => $quote,
                    'location' => $quote->location,
                    'type' => $type
                ));
                break;
            case Invoice::TYPE_INVOICE:
                $tabName = 'Invoice';
                $location = Locations::model()->find('custno=:custno AND locno=:locno', array(
                    'custno' => $custno,
                    'locno' => $locno)
                );
                if ($location == NULL) {
                    throw new CHttpException(404, 'The requested page does not exist.');
                }
                $this->render('index', array(
                    'location' => $location,
                    'type' => $type
                ));
                break;
        }
    }

    public function actionCancel($invoice) {
        $model = $this->loadModel($invoice);
        $type = $model->invoicetype;
        $locno = $model->locno;
        $custno = $model->custno;
        $quoteorg = $model->quoteorg;
        $jobid = $model->jobnumber;
        $salesordersorg = $model->salesordersorg;
        if($model->invoicetype!=Invoice::TYPE_QUOTE){
            $model->delete();
        }


        switch ($type) {
            case Invoice::TYPE_QUOTE:
                //redirect to quote list
                if ($jobid != NULL) {
                    $this->redirect(array('jobs/update', 'jobid' => $jobid));
                }else
                    $this->redirect(array('index', 'custno' => $custno, 'locno' => $locno, 'type' => $type));
                break;
            case Invoice::TYPE_SALES_ORDERS:
                //redirect to quote update page
                $this->redirect(array('update', 'invoice' => $quoteorg));
                break;
            case Invoice::TYPE_INVOICE:
                $this->redirect(array('update', 'invoice' => $salesordersorg));
                break;
        }
    }

    public function actionUpdate($invoice) {
        return;
        $model = $this->loadModel($invoice);
        SalesPortalLoginCheckerUtil::canUserAccessCustomer($model);
        
        
        $tabName    = '';
        switch ($model->invoicetype)
        {
            case Invoice::TYPE_QUOTE:
                $tabName = 'Quote';

                break;
            case Invoice::TYPE_SALES_ORDERS:
                $tabName = 'Sales Order';

                break;
            case Invoice::TYPE_INVOICE:
                $tabName = 'Invoice';
                break;
        }
        Yii::app()->clientScript->registerScript('typeLabel', "var typeLabel='$tabName'", CClientScript::POS_HEAD);


        
        outputJsByList(ContactUtil::getContactData($model->custno, $model->locno, $model->salesperson), 'contacts');
      
        outputJsByList(Warehouse::model()->getList(), 'warehouse');
        outputJsByList(Employees::model()->getEmployeeList(), 'employee');
        outputJsByList(Equipment::model()->getListByLocation($model->custno, $model->locno), 'equipment');
        $invoiceLedger = InvoiceLedger::model()->findAll('invoice=:invoice', array('invoice' => $model->invoice));
        $itemsList = array();
        foreach ($invoiceLedger as $i => $item)
        {
            $itemsList[]                    = $item->attributes;
            $itemsList[$i]['price']         = $item->price;
            $itemsList[$i]['noprinttext']   = $item->getYesNoValue($item->noprint);
            $itemsList[$i]['taxedtext']     = $item->getYesNoValue($item->taxed);
        }
          if($model->discounted){
            $discount = new InvoiceLedger();
            $discount->price = $model->discount_percent;
            $discount->description = $model->discount_memo;
            $discount->tax1 = $model->discount_tax;
            $discount->tax2 = $model->discount_amount;
            $discount->partno = 'discount';
            $discount->warehouse = '0000'; 
            $itemsList[]   = $discount->attributes;
            
        }
        Yii::app()->clientScript->registerScript('itemlist', "var invoiceLedgerList=" . json_encode($itemsList), CClientScript::POS_HEAD);
        $invoiceEmpList     = InvoiceEmp::model()->findAll('invoice=:invoice', array('invoice' => $model->invoice));
        $invoiceEmpArray    = array();
        foreach ($invoiceEmpList as $i => $item)
        {
            $invoiceEmpArray[] = $item->attributes;
            if ($item->employee != NULL)
            {
                $invoiceEmpArray[$i]['employeetext'] = $item->employee->firstname . ' ' . $item->employee->lastname;
            }
        }
        Yii::app()->clientScript->registerScript('empList', "var empList =" . json_encode($invoiceEmpArray), CClientScript::POS_HEAD);
 $transList = $model->getTransactionsList();
        $transData = array();
        foreach ($transList as $i=> $trans){
            $transData[$i]=array();
            $dateArray = explode('-',$trans['TxnDate']);

            $transData[$i]['date'] =$dateArray[1].'/'.intval($dateArray[2]).'/'.$dateArray[0];
            
            $transData[$i]['type'] =$trans['TxnType'];
            $transData[$i]['amount'] =$trans['Amount'];
            $transData[$i]['TxnID'] =$trans['TxnID'];
        }
        Yii::app()->clientScript->registerScript('transList', "var transList =" . json_encode($transData), CClientScript::POS_HEAD);
      

        //post the tax to javascript
        $tax = $model->getTaxModel();
        if ($tax == NULL)
        {
            throw new CHttpException(500, 'Please update zipcode in '
                    . CHtml::link('Location', $this->createUrl('/locations/update', array('custno' => $model->custno, 'locno' => $model->locno))));
        }
        $tax = CJSON::encode($tax->attributes);
        $isNex = $model->checkNex()?'true':'false';
        Yii::app()->clientScript->registerScript('tax', "
                var TAX_EXEMPT_YES=" . Locations::TAX_EXEMPT_YES . ";
                var TAX_EXEMPT_NO=" . Locations::TAX_EXEMPT_NO . ";
                var taxcode=$tax;
                var isExempt={$model->location->isexempt};
                var useNexTax = $isNex;
                ", CClientScript::POS_HEAD);

     


      
        $this->render('view', array(
            'model' => $model,
            'type'  => $model->invoicetype,
                )
        );
        return;
      
       
    }

    public function actionCreateQuote($jobnumber) {
        /*
          $location = Locations::model()->findByPk($locid);
          if($location==NULL){

          throw new CHttpException(404, 'The requested page does not exist.');
          }
         */
        $job = Jobs::model()->findByPk($jobnumber);
        
        if ($job == NULL) {
            throw new CHttpException(404, 'The requested page does not exist.');
        }
        SalesPortalLoginCheckerUtil::canUserAccessCustomer($job);
        $location = $job->location;
        $model = new Invoice();
        $model->invoice = date('Y') . '-' . Counters::model()->getNextNumber('invoice');
        $model->invoicedate = date('Y-m-d');
        $model->invoicetype = Invoice::TYPE_QUOTE;
        $customer = $location->customer;
        $model->jobnumber = $jobnumber;
        $model->custno = $location->custno;
        $model->locno = $location->locno;
        $model->shipaddress1 = $location->add1;
        $model->shipaddress2 = $location->add2;
        $model->shipCSZ = "$location->city $location->state $location->zip";
        $model->shipname = $location->locname;
        $model->period = date('Ym');
        $model->taxcode = $location->taxcode;

        //some default setting from parent company
        $customer = $model->customer;
        $model->salesperson = $customer->salesperson;
        $model->pricecode = $customer->pricecode;
        $model->slterms = $customer->terms;
        $model->invoicedate = date('Y-m-d');
        $model->status = 1;
        if ($model->save()) {

            $this->redirect(array('update', 'invoice' => $model->invoice));
        } else {
            return NULL;
        }
    }

    public function actionCreateSalesOrders($quoteinvoice) {

        $quote = $this->loadModel($quoteinvoice);
        if ($quote->quotestatus != Invoice::STATUS_APPROVED) {
            throw new CHttpException('This quote is not approved');
        }
        
        $model = new Invoice();
        $model->attributes = $quote->attributes;
        $model->invoice = date('Y') . '-' . Counters::model()->getNextNumber('invoice');
        $model->invoicedate = date('Y-m-d');
        $model->quoteorg = $quoteinvoice;
        $model->invoicetype = Invoice::TYPE_SALES_ORDERS;
        $model->status = 1;

        //some default setting from parent company


        if ($model->save()) {
            
            //delete all old sale orders
            Yii::app()->db->createCommand()->delete('tbl_invoice', 'quoteorg=:quote AND invoice!=:curInvoice', array(
                'quote' => $quoteinvoice,
                'curInvoice' => $model->invoice
            ));
            
            //copy item and technician
            $itemList = Yii::app()->db->createCommand('select * from tbl_invoice_ledger where invoice=:quote')->bindValue('quote', $quoteinvoice)->queryAll();
            foreach ($itemList as $item) {
                $item['invoice'] = $model->invoice;
                unset($item['id']);
                //print_r($item);
                $invoiceLedger = new InvoiceLedger;
                $invoiceLedger->attributes = $item;
                $invoiceLedger->save();
            }

            $techList = Yii::app()->db->createCommand('select * from tbl_invoice_emp where invoice=:quote')->bindValue('quote', $quoteinvoice)->queryAll();
            foreach ($techList as $item) {
                $item['invoice'] = $model->invoice;
                unset($item['id']);
                $invoiceEmp = new InvoiceEmp;
                $invoiceEmp->attributes = $item;
                $invoiceEmp->save();
            }

            $this->redirect(array('update', 'invoice' => $model->invoice));
        } else {
            return NULL;
        }
    }

    public function actionCreateInvoice($saleinvoice) {
        $sale = $this->loadModel($saleinvoice);

        $model = new Invoice();
        $model->attributes = $sale->attributes;
        $model->invoice = date('Y') . '-' . Counters::model()->getNextNumber('invoice');
        $model->invoicedate = date('Y-m-d');
        $model->salesordersorg = $saleinvoice;
        $model->invoicetype = Invoice::TYPE_INVOICE;
        $model->invoicedate = date('Y-m-d');
        $model->status = 1;

        //some default setting from parent company


        if ($model->save()) {
            $itemList = Yii::app()->db->createCommand('select * from tbl_invoice_ledger where invoice=:salesorders')->bindValue('salesorders', $saleinvoice)->queryAll();
            foreach ($itemList as $item) {
                $item['invoice'] = $model->invoice;
                unset($item['id']);
                $invoiceLedger = new InvoiceLedger;
                $invoiceLedger->attributes = $item;
                $invoiceLedger->save();
            }

            $techList = Yii::app()->db->createCommand('select * from tbl_invoice_emp where invoice=:salesorders')->bindValue('salesorders', $saleinvoice)->queryAll();
            foreach ($techList as $item) {
                $item['invoice'] = $model->invoice;
                unset($item['id']);
                $invoiceEmp = new InvoiceEmp;
                $invoiceEmp->attributes = $item;
                $invoiceEmp->save();
            }

            $this->redirect(array('update', 'invoice' => $model->invoice));
        } else {
            return NULL;
        }
    }

    public function actionGetBillToData($id, $custno) {
        $data = array();
        if ($id != 0)
            $model = Locations::model()->findByPk($id);
        else {
            $model = Customers::model()->findByPk($custno);
        };

        $data['add1'] = $model->add1;
        $data['add2'] = $model->add2;
        $data['csz'] = "$model->city $model->state $model->zip";
        echo json_encode($data);
    }

    /**
     * Returns the json endcoded item params(price, etc)
     * @param string item description
     */
    public function actionGetItemData($description) {

        //echo $description;

        $criteria = new CDbCriteria;
        $criteria->compare('description', $description);
        $model = Inventory::model()->find($criteria);


        $data = array();
        $data['price'] = $model->baseprice;
        $data['partno'] = $model->partno;

        echo json_encode($data);
    }

    public function actionGetInvoiceLists($locid=NULL,$locno=NULL,$custno=NULL, $pk=NULL, $type=NULL, $page=1, $sort=NULL, $dir=NULL) {
        //we decrease $page by 1 because in Extjs first page is 1, but in our sql first page is 0;
        if ($page > 0)
            $page--;
        $crit = new CDbCriteria();
        switch ($type) {

            case Invoice::TYPE_QUOTE:
                $crit->condition = 'invoicetype=:type';
                $crit->params = array(
                    'type' => $type,
                );
                break;
            case Invoice::TYPE_SALES_ORDERS:
                $crit->condition = 'invoicetype=:type  AND quoteorg=:quote';
                $crit->params = array(
                    'type' => $type,
                    'quote' => $pk,
                );
                break;
            case Invoice::TYPE_INVOICE:
                $crit->condition = 'invoicetype=:type AND custno=:custno AND locno=:locno';
                $crit->params = array(
                    'type' => $type,
                    'custno'=>$custno,
                    'locno'=>$locno
                );
                break;
            case Invoice::TYPE_CREDIT_MEMO:
                break;
            default:
                return;
        }
        $crit->order = $sort != NULL ? $sort . ' ' . $dir : '';
        $invoiceList = new CActiveDataProvider('Invoice', array(
                    'criteria' => $crit,
                    'pagination' => array(
                        'pageSize' => 20,
                        'currentPage' => $page,
                    ),
                ));

        $invoiceArr = array();
        if ($invoiceList->getTotalItemCount() > 0) {
            $invoiceArr['totalCount'] = $invoiceList->getTotalItemCount();
            $invoiceArr['type'] = 'Items';
            foreach ($invoiceList->getData() as $i => $item) {
                $invoiceArr['data'][] = $item->getAttributes();
                $invoiceArr['data'][$i]['totaltax'] = number_format($item->getTotalTax(), 2);
                $invoiceArr['data'][$i]['subtotal'] = number_format($item->getSubTotal(), 2);
                //$invoiceArr['data'][$i]['total']=$item->getTotal();
            }
            echo json_encode($invoiceArr);
        }
        Yii::app()->end();
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Invoice::model()->findByPk($id);
        SalesPortalLoginCheckerUtil::canUserAccessCustomer($model);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    public function actionCheckQuoteApproved($quote) {
        $model = $this->loadModel($quote);
        if ($model->quotestatus == Invoice::STATUS_APPROVED) {
            echo 'true';
        } else {
            echo 'false';
        }
    }
    
    public function actionViewSalesOrder($invoice){
        $model=$this->loadModel($invoice);
        $salesOrder=$model->getSalesOrders();
        if($model->invoicetype==Invoice::TYPE_QUOTE && $salesOrder!=NULL){
            $this->redirect(array('invoices/update','invoice'=>$salesOrder->invoice));
        }else{
            throw new CHttpException(404, 'The requested page does not exist.');
        }
    }
    public function actionViewInvoice($invoice){
        $model=$this->loadModel($invoice);
        $invoiceModel=$model->getInvoiceModel();
        if($model->invoicetype==Invoice::TYPE_SALES_ORDERS && $invoiceModel!=NULL){
            $this->redirect(array('invoices/update','invoice'=>$invoiceModel->invoice));
        }else{
            throw new CHttpException(404, 'The requested page does not exist.');
        }
    }
}

?>
